package com.zhs.gccs.activity.app;

import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.blankj.utilcode.constant.PermissionConstants;
import com.blankj.utilcode.util.AppUtils;
import com.gyf.immersionbar.ImmersionBar;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadLargeFileListener;
import com.liulishuo.filedownloader.FileDownloader;
import com.zhs.gccs.R;
import com.zhs.gccs.base.BaseActivity;
import com.zhs.gccs.http.Api;
import com.zhs.gccs.http.ProgressObserver;
import com.zhs.gccs.model.AppVersion;
import com.zhs.gccs.model.AppVersionBean;
import com.zhs.gccs.utils.FileUtils;
import com.zhs.gccs.utils.GsonImpl;
import com.zhs.gccs.utils.OnNoDoubleClickListener;
import com.zhs.gccs.utils.PackageUtil;
import com.zhs.gccs.utils.PermissionListener;
import com.zhs.gccs.utils.SharedPrefHelper;
import com.zhs.gccs.utils.ToastUtils;
import com.zhs.gccs.utils.Utils;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.RequestBody;

public class AppVersionActivity extends BaseActivity {
    @BindView(R.id.ll_bar)
    LinearLayout ll_bar;
    @BindView(R.id.iv_back)
    View iv_back;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.tv_version_current)
    TextView tv_version_current;
    @BindView(R.id.tv_version_latest)
    TextView tv_version_latest;
    @BindView(R.id.tv_version_remarks)
    TextView tv_version_remarks;
    @BindView(R.id.tv_download_app)
    TextView tv_download_app;

    @BindView(R.id.id_progress_app)
    ProgressBar id_progress_app;
    @BindView(R.id.tv_app_current)
    TextView tv_app_current;
    @BindView(R.id.tv_app_size)
    TextView tv_app_size;

    @BindView(R.id.ll_update)
    View ll_update;

    private AppVersion appVersion;
    private long totalSize = 0;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_version);
//        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        ButterKnife.bind(this);
//        ImmersionBar.with(this)
//                .transparentBar()
//                .statusBarDarkFont(false)
//                .init();
        ImmersionBar.with(this).transparentBar().statusBarDarkFont(false).init();
        ll_bar.setPadding(0, ImmersionBar.getStatusBarHeight(this), 0, 0);
        iv_back.setOnClickListener(new OnNoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                finish();
            }
        });
        tv_download_app.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                if(appVersion!=null&&appVersion.getPath()!=null){
                    tv_download_app.setClickable(false);
                    tv_download_app.setText("下载中");
                    downloadApk("核查APP_"+appVersion.getAppVersionCode()+".apk",appVersion.getPath());
                }
            }
        });
        initPermission();
    }

    private void downloadApk(String fileName,String url) {
        String file = Utils.getMainPath(context) + "/" + fileName;
        FileUtils.deleteFile(file);
        FileDownloadLargeFileListener fileDownloadLargeFileListener = new FileDownloadLargeFileListener() {
            @Override
            protected void pending(BaseDownloadTask task, long soFarBytes, long totalBytes) {

            }

            @Override
            protected void progress(BaseDownloadTask task, long soFarBytes, long totalBytes) {
                id_progress_app.setProgress((int) (soFarBytes * 100.0 / totalBytes));
                totalSize = totalBytes;
                setViewText(tv_app_size, totalBytes);
                setViewText(tv_app_current, soFarBytes);
            }

            @Override
            protected void paused(BaseDownloadTask task, long soFarBytes, long totalBytes) {

            }

            @Override
            protected void completed(BaseDownloadTask task) {
                id_progress_app.setProgress(100);
                setViewText(tv_app_current, totalSize);
                tv_download_app.setClickable(true);
                tv_download_app.setText("更新");
                ToastUtils.toast("下载APK完成");
                AppUtils.installApp(file);
            }

            @Override
            protected void error(BaseDownloadTask task, Throwable e) {
                ToastUtils.toast("下载APP失败");
                tv_download_app.setClickable(true);
                tv_download_app.setText("更新");
//                task.start();
            }

            @Override
            protected void warn(BaseDownloadTask task) {

            }
        };
        FileDownloader.getImpl()
//                .create(BuildConfig.BASEURL + "check/task/file/download/" + type + "/" +
//                        SharedPrefHelper.getInstance().getTaskId())
                .create(url)
                .addHeader("Authorization", "Bearer " + SharedPrefHelper.getInstance().getToken())
                .setPath(Utils.getMainPath(context) + "/" + fileName)
                .setTag(fileName)
                .setListener(fileDownloadLargeFileListener)
                .start();
    }
    private void setViewText(TextView tv, long size) {
        tv.setText(readableFileSize(size));
    }

    public static String readableFileSize(long size) {
        if (size <= 0) {
            return "0";
        }
        final String[] units = new String[]{"B", "KB", "MB", "GB", "TB"};
        int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
        return new DecimalFormat("#,###.##")
                .format(size / Math.pow(1024, digitGroups)) + " " + units[digitGroups];
    }

    void initPermission() {
        requestPermission(context, new PermissionListener() {
            @Override
            public void onSucceed() {
                checkAppVersion();
            }

            @Override
            public void onFailed() {
                initPermission();
            }
        }, PermissionConstants.STORAGE);
    }
    private void checkAppVersion() {
        Map data = new HashMap();
        try {
            data.put("packageName", PackageUtil.getPackageName(context));
        } catch (Exception e) {
        }
        RequestBody requestBody = createRequestBody(data);
        toSubscribeSingleOb(Api.getDefault().appLatestVersion2(requestBody),
                new ProgressObserver(this, false) {
                    @Override
                    protected void _onNext(String result) {
                        AppVersionBean bean = GsonImpl.get().toObject(result, AppVersionBean.class);
                        if(bean!=null&&bean.getCode()==200
                                &&bean.getData()!=null&&bean.getData().getAppVersionCode()!=null){
                            appVersion = bean.getData();
                            updateUi();
                        }
                    }
                    @Override
                    protected void _onError(String result) {
                    }
                });
    }

    private void updateUi() {
        tv_version_current.setText(AppUtils.getAppVersionName());
        if(appVersion==null)return;
        tv_version_latest.setText(appVersion.getAppVersionName());
        int appVersionCode = AppUtils.getAppVersionCode();
        if(appVersionCode<appVersion.getAppVersionCode()){
            ll_update.setVisibility(View.VISIBLE);
        }else {
            ll_update.setVisibility(View.GONE);
        }
        tv_version_remarks.setText(appVersion.getUpdateRemarks());
    }

}
